package model

import (
	"math/rand"
	"sync"
	"time"
)

type QpsManager struct {
	initLock chan bool
	QMap     sync.Map
}

func (q *QpsManager) Init() {
	q.initLock = make(chan bool, 1)
	q.initLock <- true
}

func (q *QpsManager) Request(path string, targetQps int64) bool {
	rawQsForId, ok := q.QMap.Load(path)
	var qsForId [10][10]int64
	var now = time.Now().UnixMilli()
	if ok {
		qsForId = rawQsForId.([10][10]int64)
		min := int64(4102416000000)
		max := int64(946656000000)
		total := 0
		for i := 0; i < 10; i++ {
			for j := 0; j < 10; j++ {
				var t = qsForId[i][j]
				if now-t < 600000 {
					total++
					if max < t {
						max = t
					}
					if min > t {
						min = t
					}
				}
			}
		}
		var qps float64
		if max == min {
			qps = float64(total)
		} else {
			qps = float64(total) / float64(max-min)
		}
		if qps >= float64(targetQps) {
			return false
		}
	} else {
		<-q.initLock
		var m [10][10]int64
		qsForId = m
		q.initLock <- true
	}
	randI := rand.Intn(10)
	randJ := rand.Intn(10)
	qsForId[randI][randJ] = now
	q.QMap.Store(path, qsForId)
	return true
}

func init() {
	rand.Seed(time.Now().Unix())
}
